package com.hqu.environment.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



/**
 * @Description: filter:  设置请求头为指定域名，实现前后端分离
 * @Author: 邓勇嘉
 * @Date:2018/11/19 18:12
 * */



public class HeadersCORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    /*
    * 设置response请求头的信息 Access-Control-Allow-Origin：* 表示所有域名地址都可以请求
    * */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //HttpServletRequest request = (HttpServletRequest) servletRequest;


        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        //设置允许携带的自定义header,用于存放token字段
        response.setHeader("Access-Control-Allow-Headers", "X-token,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        //System.out.println( request.getHeader("Origin"));
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override


    public void destroy() {

    }

}
